using Android.App;
using Android.OS;
using Android.Views;
using Android.Widget;
using AF.Data;
using AF.Models;

namespace AF.Activities
{
    [Activity(Label = "统计报表", Theme = "@android:style/Theme.Material.Light.NoActionBar")]
    public class StatisticsActivity : Activity
    {
        private DatabaseHelper? dbHelper;
        private Button? btnThisMonth;
        private Button? btnLastMonth;
        private Button? btnThisYear;
        private TextView? textPeriod;
        private TextView? textStatIncome;
        private TextView? textStatExpense;
        private TextView? textStatBalance;
        private ListView? listViewIncome;
        private ListView? listViewExpense;

        private DateTime startDate;
        private DateTime endDate;
        private string periodText = "";

        protected override void OnCreate(Bundle? savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_statistics);

            dbHelper = new DatabaseHelper(this);

            InitializeViews();
            SetupEventHandlers();
            
            // 默认显示本月统计
            ShowThisMonth();
        }

        private void InitializeViews()
        {
            btnThisMonth = FindViewById<Button>(Resource.Id.btnThisMonth);
            btnLastMonth = FindViewById<Button>(Resource.Id.btnLastMonth);
            btnThisYear = FindViewById<Button>(Resource.Id.btnThisYear);
            textPeriod = FindViewById<TextView>(Resource.Id.textPeriod);
            textStatIncome = FindViewById<TextView>(Resource.Id.textStatIncome);
            textStatExpense = FindViewById<TextView>(Resource.Id.textStatExpense);
            textStatBalance = FindViewById<TextView>(Resource.Id.textStatBalance);
            listViewIncome = FindViewById<ListView>(Resource.Id.listViewIncome);
            listViewExpense = FindViewById<ListView>(Resource.Id.listViewExpense);
        }

        private void SetupEventHandlers()
        {
            if (btnThisMonth != null)
                btnThisMonth.Click += (s, e) => ShowThisMonth();

            if (btnLastMonth != null)
                btnLastMonth.Click += (s, e) => ShowLastMonth();

            if (btnThisYear != null)
                btnThisYear.Click += (s, e) => ShowThisYear();
        }

        private void ShowThisMonth()
        {
            var now = DateTime.Now;
            startDate = new DateTime(now.Year, now.Month, 1);
            endDate = startDate.AddMonths(1).AddDays(-1);
            periodText = now.ToString("yyyy年MM月");
            
            UpdateButtonStates(1);
            LoadStatistics();
        }

        private void ShowLastMonth()
        {
            var now = DateTime.Now;
            var lastMonth = now.AddMonths(-1);
            startDate = new DateTime(lastMonth.Year, lastMonth.Month, 1);
            endDate = startDate.AddMonths(1).AddDays(-1);
            periodText = lastMonth.ToString("yyyy年MM月");
            
            UpdateButtonStates(2);
            LoadStatistics();
        }

        private void ShowThisYear()
        {
            var now = DateTime.Now;
            startDate = new DateTime(now.Year, 1, 1);
            endDate = new DateTime(now.Year, 12, 31);
            periodText = now.ToString("yyyy年");
            
            UpdateButtonStates(3);
            LoadStatistics();
        }

        private void UpdateButtonStates(int activeButton)
        {
            var activeColor = Android.Graphics.Color.ParseColor("#2196F3");
            var inactiveColor = Android.Graphics.Color.ParseColor("#E0E0E0");

            btnThisMonth?.SetBackgroundColor(activeButton == 1 ? activeColor : inactiveColor);
            btnLastMonth?.SetBackgroundColor(activeButton == 2 ? activeColor : inactiveColor);
            btnThisYear?.SetBackgroundColor(activeButton == 3 ? activeColor : inactiveColor);
        }

        private void LoadStatistics()
        {
            if (dbHelper == null) return;

            // 更新期间标题
            if (textPeriod != null)
                textPeriod.Text = periodText;

            // 获取统计数据
            var (totalIncome, totalExpense, balance) = dbHelper.GetStatistics(startDate, endDate);

            if (textStatIncome != null)
                textStatIncome.Text = $"¥{totalIncome:N2}";

            if (textStatExpense != null)
                textStatExpense.Text = $"¥{totalExpense:N2}";

            if (textStatBalance != null)
                textStatBalance.Text = $"¥{balance:N2}";

            // 获取交易记录并按分类统计
            var transactions = dbHelper.GetTransactionsByDateRange(startDate, endDate);
            
            var incomeStats = GetCategoryStatistics(transactions, TransactionType.Income, totalIncome);
            var expenseStats = GetCategoryStatistics(transactions, TransactionType.Expense, totalExpense);

            // 显示收入明细
            if (listViewIncome != null)
            {
                var incomeAdapter = new CategoryStatAdapter(this, incomeStats);
                listViewIncome.Adapter = incomeAdapter;
                SetListViewHeightBasedOnChildren(listViewIncome);
            }

            // 显示支出明细
            if (listViewExpense != null)
            {
                var expenseAdapter = new CategoryStatAdapter(this, expenseStats);
                listViewExpense.Adapter = expenseAdapter;
                SetListViewHeightBasedOnChildren(listViewExpense);
            }
        }

        private List<CategoryStatItem> GetCategoryStatistics(
            List<Transaction> transactions, TransactionType type, decimal total)
        {
            var stats = transactions
                .Where(t => t.Type == type)
                .GroupBy(t => t.CategoryName)
                .Select(g => new CategoryStatItem
                {
                    CategoryName = g.Key,
                    Amount = g.Sum(t => t.Amount),
                    Percentage = total > 0 ? (double)(g.Sum(t => t.Amount) / total * 100) : 0
                })
                .OrderByDescending(s => s.Amount)
                .ToList();

            return stats;
        }

        private void SetListViewHeightBasedOnChildren(ListView listView)
        {
            var adapter = listView.Adapter;
            if (adapter == null) return;

            int totalHeight = 0;
            for (int i = 0; i < adapter.Count; i++)
            {
                View? listItem = adapter.GetView(i, null, listView);
                if (listItem != null)
                {
                    listItem.Measure(0, 0);
                    totalHeight += listItem.MeasuredHeight;
                }
            }

            ViewGroup.LayoutParams? parameters = listView.LayoutParameters;
            if (parameters != null)
            {
                parameters.Height = totalHeight + (listView.DividerHeight * (adapter.Count - 1));
                listView.LayoutParameters = parameters;
            }
        }
    }

    public class CategoryStatItem
    {
        public string CategoryName { get; set; } = "";
        public decimal Amount { get; set; }
        public double Percentage { get; set; }
    }

    public class CategoryStatAdapter : BaseAdapter<CategoryStatItem>
    {
        private readonly Activity context;
        private readonly List<CategoryStatItem> items;

        public CategoryStatAdapter(Activity context, List<CategoryStatItem> items)
        {
            this.context = context;
            this.items = items;
        }

        public override CategoryStatItem this[int position] => items[position];

        public override int Count => items.Count;

        public override long GetItemId(int position) => position;

        public override View? GetView(int position, View? convertView, ViewGroup? parent)
        {
            var view = convertView ?? context.LayoutInflater.Inflate(
                Resource.Layout.list_item_category_stat, null);

            var item = items[position];

            var textCategoryName = view?.FindViewById<TextView>(Resource.Id.textCategoryName);
            var textAmount = view?.FindViewById<TextView>(Resource.Id.textAmount);
            var textPercentage = view?.FindViewById<TextView>(Resource.Id.textPercentage);

            if (textCategoryName != null)
                textCategoryName.Text = item.CategoryName;

            if (textAmount != null)
                textAmount.Text = $"¥{item.Amount:N2}";

            if (textPercentage != null)
                textPercentage.Text = $"{item.Percentage:F1}%";

            return view;
        }
    }
}

